package com.xetlab.zk.autoconfigure;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.CuratorFrameworkFactory.Builder;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author xingyi
 */
@Configuration
@ConditionalOnClass(CuratorFramework.class)
@EnableConfigurationProperties(ZkProperties.class)
public class ZkAutoConfiguration {

    @Autowired
    private ZkProperties zkProperties;

    @Bean
    public CuratorFramework curatorFramework() {
        final Builder builder = CuratorFrameworkFactory.builder()
                .connectString(zkProperties.getConnectString())
                .retryPolicy(new ExponentialBackoffRetry(1000, 3));
        if (zkProperties.getConnectionTimeoutMs() != null) {
            builder.connectionTimeoutMs(zkProperties.getConnectionTimeoutMs());
        }
        if (zkProperties.getSessionTimeoutMs() != null) {
            builder.sessionTimeoutMs(zkProperties.getSessionTimeoutMs());
        }
        CuratorFramework curatorFramework = builder
                .build();
        curatorFramework.start();
        return curatorFramework;
    }
}
